import React, { Component } from 'react'
import { Row, Col, Checkbox, Spin, Button, Modal, Input, Tooltip } from 'antd';
const CheckboxGroup = Checkbox.Group;
const Search = Input.Search;

class ShopGroups extends Component {
  constructor(props) {
    super(props);
    this.state = {
      optionList: props.data.shopList.map(item=> item.shopId),
      checkedList: [],
      indeterminate: false,
      checkAll: false,
    };
  }

  componentDidMount () {
    const { checkedList } = this.props;
    const totalLength = this.state.optionList.length;
    this.setState({
      checkedList: checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < totalLength),
      checkAll: checkedList.length === totalLength,
    })
  }

  componentWillReceiveProps(nextProps) {
    const { checkedList } = nextProps;
    const totalLength = this.state.optionList.length;
    this.setState({
      checkedList: checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < totalLength),
      checkAll: checkedList.length === totalLength,
    })
  }

  onChange = (checkedList) => {
    const totalLength = this.state.optionList.length;
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < totalLength),
      checkAll: checkedList.length === totalLength,
    });
    this.props.callback(this.props.data.city, checkedList);
  }

  onCheckAllChange = (e) => {
    const checkedList = e.target.checked ? this.state.optionList : []
    this.setState({
      checkedList: checkedList,
      indeterminate: false,
      checkAll: e.target.checked,
    });
    this.props.callback(this.props.data.city, checkedList);
  }

  handleLabelTooltip = (label) => {
    if(label.length > 8){
      return (<Tooltip placement="right" title={label}>
        {`${label.substring(0,7)}...`}
      </Tooltip>)
    } else {
      return label;
    }
  }

  render() {
    const {data} = this.props;
    return (
        <div>
          <div style={{ borderBottom: '1px solid #E9E9E9', padding: '5px 0', fontWeight: 900 }}>
            <Checkbox
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
                >
              {data.city}
            </Checkbox>
          </div>
          {/*<CheckboxGroup onChange={this.onChange}
                         value={this.state.checkedList}
                         options={data.shopList.map(item=>({value: item.shopId,
                                                            label: item.shopNameAlias}))}/>*/}
          <CheckboxGroup onChange={this.onChange} value={this.state.checkedList}>
            {data.shopList.map(item =>
              <Checkbox key={item.shopId} value={item.shopId} style={{width: 126, marginTop: 5}}>
                {this.handleLabelTooltip(item.shopNameAlias)}
              </Checkbox>
            )}
          </CheckboxGroup>,
        </div>
    )
  }
}

/***************************************************************************************************************/

class UserShop extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentUser: {
        userId: props.userList[0].userId,
        userName: props.userList[0].userName
      },
      selectShops: {},
      allSelectShop: {},
      shopListTotal: 0,
      userShopTotal: 0,
      widowHeight: document.body.offsetHeight
    }
  }

  componentDidMount() {
    window.addEventListener('resize', this.onWindowResize)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onWindowResize)
  }

  onWindowResize = () => {
    this.setState({
      //widowWidth: document.body.offsetWidth,
      widowHeight: document.body.offsetHeight
    })
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.currentShopUser !== nextProps.currentShopUser){
      this.handleSelectShops(nextProps.userShop, nextProps.userShopTotal)
    }
    if(this.props.shopList.length === 0 && nextProps.shopList.length > 0){
      let allSelectShop = {};
      nextProps.shopList.forEach(item => {
        allSelectShop[item.city] = item.shopList.map(itemShops => {
          return itemShops.shopId
        })
      })
      this.setState({
        allSelectShop: allSelectShop,
        shopListTotal: nextProps.shopListTotal
      })
    }
  }

  //处理默认已选门店的数据格式
  handleSelectShops = (userShop, total) => {
    let selectShops = {};
    userShop.forEach(item => {
      selectShops[item.city] = item.shopList.slice();
    })
    this.setState({
      selectShops: selectShops,
      userShopTotal: total
    })
  }

  //选择用户
  handleChooseUser = (user) => {
    this.setState({
      currentUser: {userId: user.userId, userName: user.userName}
    })
    this.props.onUserChoose(user.userId);
  }

  //选择门店操作
  handleShopChange = (city, shopList) => {
    let _selectShops = this.state.selectShops, total = 0;
    _selectShops[city] = shopList;
    for(let key in _selectShops) {
      if(_selectShops[key].length > 0) {
        total += _selectShops[key].length
      }
    }
    this.setState({
      selectShops: _selectShops,
      userShopTotal: total
    })
  }

  //全选切换
  handleCheckAllChange = (e) => {
    console.log(e);
    console.log(this.state.allSelectShop);
    if(e.target.checked){
      this.setState({
        userShopTotal: this.props.shopListTotal,
        selectShops: Object.assign({}, this.state.allSelectShop)
      })
    } else {
      this.setState({
        userShopTotal: 0,
        selectShops: {}
      })
    }
  }

  //保存用户门店信息
  handleShopSave = () => {
    const {currentUser, selectShops} = this.state;
    const {onUserShopSave} = this.props;
    let shopList = [];
    for(let key in selectShops) {
      if(selectShops[key].length > 0) {
        shopList = shopList.concat(selectShops[key]);
      }
    }
    Modal.confirm({
      title: `确认修改用户 ${currentUser.userName} 下关联的门店信息？`,
      onOk() {
        return onUserShopSave({
          userId: currentUser.userId,
          userName: currentUser.userName,
          shopList: shopList
        });
      },
      onCancel() {},
    });
  }

  //取消用户门店信息，重新获取数据
  handleShopSaveCancel = () => {
    this.handleSelectShops(this.props.userShop, this.props.userShopTotal);
  }

  render() {
    const { userList, shopList, loading, onUserSearch, searchLoading } = this.props;
    const { widowHeight} = this.state;
    return (
        <div className="user_shop" style={{height: widowHeight - 135}}>
            <div className="user_ulist">
              <p className="title">选择用户</p>
              <Search
                  placeholder="查询用户"
                  style={{ width: 170, margin: '10px 0' }}
                  onSearch={value => onUserSearch(value)}
                  />
              <Spin spinning={searchLoading} delay={500}>
                <ul className="user_select">
                  {userList.map(item =>
                          <li key={item.key}
                              onClick={() => this.handleChooseUser(item)}
                              className={this.state.currentUser.userId === item.userId ? 'active' : ''}>
                            {item.userName}
                          </li>
                  )}
                </ul>
              </Spin>
            </div>
            <div className="user_slist">
              <p className="title">选择门店</p>
              <Spin spinning={loading}>
                {shopList.length > 0 ?
                    <div className="user_slist_container" style={{height: widowHeight - 160}}>
                      <Checkbox className="user_slist_top"
                                indeterminate={this.state.userShopTotal > 0 && this.state.userShopTotal < this.state.shopListTotal}
                                checked={this.state.userShopTotal === this.state.shopListTotal}
                                onChange={this.handleCheckAllChange}>全选</Checkbox>
                      <div className="user_slist_main">
                        {shopList.map((item,index) =><ShopGroups key={index}
                                                                 value={item.city}
                                                                 data={item}
                                                                 checkedList={this.state.selectShops[item.city] || []}
                                                                 callback={this.handleShopChange}/>) }
                      </div>
                      <div className="user_slist_button">
                        <Button onClick={this.handleShopSaveCancel}>取消</Button>
                        <Button type="primary" style={{marginLeft: 8}}
                                onClick={this.handleShopSave}>保存</Button>
                      </div>
                    </div> : null}
              </Spin>
            </div>
        </div>
    )
  }
}

export default UserShop
